const nodemailer = require('nodemailer');
const fs = require('fs');
const path = require('path');

// 读取签名模板
const signatureTemplate = fs.readFileSync('./src/signature.html', 'utf8');
let contentWithBrArray = [];

// 读取 content0.txt 到 content9.txt 文件内容
for (let i = 0; i < 10; i++) {
    const contentPath = path.join(__dirname, `content${i}.txt`);
    fs.readFile(contentPath, 'utf8', (err, contentText) => {
        if (err) {
            console.error(`读取 content${i}.txt 失败:`, err);
            return;
        }
        // 将 content.txt 的内容中的换行符转换为 <br> 标签
        contentWithBrArray.push(contentText.replace(/\n/g, '<br>'));
    });
}

// 读取 email.txt 文件内容
const emailPath = path.join(__dirname, 'email.txt');
fs.readFile(emailPath, 'utf8', (err, emailData) => {
    if (err) {
        console.error(`读取 email.txt 失败:`, err);
        return;
    }

    // 提取 target、mail、pws 和 mailTitle 字段
    const contentPathJson = path.join(__dirname, 'content.json');
    fs.readFile(contentPathJson, 'utf8', (err, jsonData) => {
        if (err) {
            console.error(`读取 content.json 失败:`, err);
            return;
        }

        // 解析 JSON 数据
        const content = JSON.parse(jsonData);

        // 提取 mail、pws 和 mailTitle 字段
        const mail = content.mail;
        const pws = content.pws;
        const mailTitles = content.title;

        // 将 email.txt 的内容按行分割成数组
        const recipients = emailData.split(';').map(email => email.trim());

        // 将 recipients 分成每组60个
        const segments = [];
        const segmentSize = 60;

        for (let i = 0; i < recipients.length; i += segmentSize) {
            segments.push(recipients.slice(i, i + segmentSize));
        }
        let segmentIndex = 0;

        // 创建一个 SMTP 传输对象
        const transporter = nodemailer.createTransport({
            host: 'smtp.qiye.aliyun.com', // 阿里云邮箱的 SMTP 服务器地址
            port: 465, // 端口号，通常为 465 (SSL) 或 25 (TLS)
            secure: true, // 使用 SSL
            auth: {
                user: mail, // 你的 Foxmail 邮箱地址
                pass: pws // 你的 Foxmail 邮箱密码
            }
        });

        // 读取 icon.png 文件
        const iconPath = path.join(__dirname, 'icon.png');
        const icon = fs.readFileSync(iconPath);

        // 定义邮件内容
        let mailOptions = {
            from: mail, // 发件人邮箱
            subject: '', // 邮件主题
            html: '', // 邮件正文
            attachments: [
                {
                    filename: 'icon.png',
                    content: icon,
                    cid: 'icon@flyingdolphinfreight.com' // 设置 CID
                }
            ]
        };
        let interval = -1;

        function getFormattedTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 定时发送邮件的函数
        function sendEmails() {
            const segmentRecipients = segments[segmentIndex];
            let sendCount = 0; 
            let intervalTime = setInterval(() => {
                if (sendCount >= segmentRecipients.length) {
                    clearInterval(intervalTime);
                    return;
                }
                mailOptions = {
                    from: mail, // 发件人邮箱
                    subject: mailTitles[Math.floor(Math.random() * mailTitles.length)], // 邮件主题
                    html: signatureTemplate.replace('{{ content }}', contentWithBrArray[Math.floor(Math.random() * contentWithBrArray.length)]), // 邮件正文
                    attachments: [
                        {
                            filename: 'icon.png',
                            content: icon,
                            cid: 'icon@flyingdolphinfreight.com' // 设置 CID
                        }
                    ],
                    to: segmentRecipients[sendCount] // 设置当前收件人
                };
                transporter.sendMail(mailOptions, (error, info) => {
                    if (error) {
                        console.error(`[${getFormattedTime()}] 发送邮件给 ${segmentRecipients[sendCount]} 失败:`, error);
                    } else {
                        console.log(`[${getFormattedTime()}] 邮件已成功发送给 ${info.accepted[0]}:`, info.response);
                    }
                });
                sendCount++;
                if (sendCount >= segmentRecipients.length) {
                    clearInterval(intervalTime);
                }
            }, 1000 + Math.floor(Math.random() * 3000));

            segmentIndex++;
            if (segmentIndex >= segments.length) {
                clearInterval(interval);
                interval = -1;
            }
        }
        // 启动时立即发送一次
        sendEmails();
        const intervalTime = 30 * 60 * 1000 + Math.floor(Math.random() * 5);
        interval = setInterval(sendEmails, intervalTime);
    });
});